﻿// //文档就绪函数
$(function () {
    show();
})
var totalCount = 0;
var pageIndex = 1;
var pageSize = 100;
//入库状态下拉框
layui.use('form', function () {
    var form = layui.form;
    $.ajax({
        url: "/Warehouse/GetAduiStatusShow",
        type: "get",
        data: { token: localStorage.getItem("token") },
        success: function (data) {
            var data = JSON.parse(data);
            //console.log(data)
            var options = '<option value="">请选择</option>'; // 添加默认选项
            $.each(data, function (index, item) {
                options += '<option value="' + item.value + '">' + item.text + '</option>';
            });
            $("#storageStatus").html(options);
            form.render('select'); // 重新渲染下拉框
        },
        error: function () {
            console.log("获取数据失败");
            // 可以考虑显示一个错误消息给用户
        }
    });
});
//入库显示
function show() {
    layui.use('table', function () {
         var form = layui.form;
        var table = layui.table;
        //查询
        var storageNo = $("#storageNo").val();
        var storageType = $("#storageType").val();
        var storageStatus = $("#storageStatus").val();
        $.ajax({
            url: "/Warehouse/GetStorageShow",
            type: "get",
            data: {
                storageNo: storageNo,
                storageType: storageType,
                storageStatus: storageStatus,
                pageIndex: pageIndex,
                pageSize: pageSize,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var res = JSON.parse(res);
                if (res.code === 0) {
                    console.log(res.data.list)
                    table.render({
                        elem: storageData,//对应HTML中表格的id
                        data: res.data.list,//绑定获取的数据
                        toolbar: '#toolbarDemo',//导出
                        defaultToolbar: ['exports', 'print'],//导出
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'storageNo', title: '订单号', width: 120 },
                            { field: 'productName', title: '产品名称', width: 140 },
                            { field: 'productNo', title: '产品编号', width: 110 },
                            { field: 'batch', title: '批次', width: 110 },
                            { field: 'productSpec', title: '规格', width: 110 },
                            { field: 'storageNum', title: '数量', width: 110 },
                            { field: 'binLocationName', title: '库位', width: 120 },
                            { field: 'storageType', title: '入库类型', width: 110 },
                            { field: 'vendorName', title: '供应商', width: 110 },
                            { field: 'singleMaker', title: '制单人', width: 80 },
                            { field: 'storageStatusTest', title: '状态', width: 120 },
                            { field: 'examinePeople', title: '审核人', width: 100 },
                            {
                                field: 'examineTime', title: '审核时间', templet: function (d) {
                                    return formatTime(d.examineTime);
                                }, width: 170
                            },
                            {
                                field: '', title: '操作', templet: function (d) {
                                    return '<a class="layui-btn layui-btn-edit layui-btn-xs" lay-on="test-page-edit" onclick="updateData(' + d.storageId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +
                                        '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.storageProductsId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>' +
                                        '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="storagemodel(' + d.storageId + ')"><i class="layui-icon layui-icon-search"></i>查看</a>' +
                                        '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="storageaudit(' + d.storageId + ')"><i class="layui-icon layui-icon-share"></i>审核</a>';
                                }
                            }
                        ]],//<button id="printButton" class="layui-btn layui-btn-normal">打印</button>
                        page: true, // 是否显示分页
                        count: totalCount,
                        limits: [15, 20, 25],
                        limit: 15,// 每页默认显示的数量
                        curr: pageIndex,
                    })
                } else {
                    console.log(res.msg);
                }
            },
            error: function () {
                console.log("获取数据失败");
                // 可以考虑显示一个错误消息给用户
            }
        });

        // 审批
        window.storageaudit = function (storageId) {
            // 先根据id获取要编辑的数据，发起Ajax请求
            $.ajax({
                type: "get",
                url: "/Warehouse/GetFanStorage",  // 替换为实际的后台根据id获取数据的接口地址
                data: {
                    storageId: storageId,
                    token: localStorage.getItem("token")
                },
                success: function (res) {
                    try {
                        const { data } = JSON.parse(res);
                        //console.log(data)
                        if (data) {
                            const { storageProductData } = data;
                            var storage = data;
                            console.log(storage);
                            console.log(storageProductData);
                            // 反填表单的函数
                            fillForm(storage);
                            //渲染表格的函数
                            layui.use('table', function () {
                                var table = layui.table;
                                if (storageProductData) {
                                    var inst = table.render({
                                        elem: '#auditDetails', // 对应HTML中表格的id
                                        data: storageProductData, // 绑定获取的数据
                                        cols: [[
                                            { field: 'productName', title: '产品名称' },
                                            { field: 'productNo', title: '产品编码' },
                                            { field: 'productSpec', title: '规格' },
                                            { field: 'batch', title: '批次' },
                                            { field: 'price', title: '单价' },
                                            { field: 'storageNum', title: '入库数' },
                                            { field: 'totalPrice', title: '总价' },
                                            { field: 'binLocationName', title: '库位' },
                                        ]],
                                    });
                                }
                            });
                            //renderTable(storageProductData);
                            resolve(storage, storageProductData);
                        } else {
                            layui.layer.msg(res.message, { icon: 2 });
                            reject(res.message);
                        }
                    } catch (e) {
                        //console.error(e);
                        //layui.layer.msg('数据解析失败，请稍后重试', { icon: 2 });
                        //reject('数据解析失败');
                    }
                },
            });

            layer.open({
                type: 1,
                title: '入库单审核',
                content: `
                      <form class="layui-form" action="">
    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">入库单号</label>
            <div class="layui-input-inline">
                <input type="text" name="storageNos" id="storageNos" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">入库单类型</label>
            <div class="layui-input-inline">
                <input type="text" id="storageTypes" name="storageTypes" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">入库状态</label>
            <div class="layui-input-inline">
                <input type="text" id="storageStatusTest" name="storageStatusTest" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">供应商编号</label>
            <div class="layui-input-inline">
                <input type="text" name="vendorNo" id="vendorNo" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">供应商名称</label>
            <div class="layui-input-inline">
                <input type="text" name="vendorName" id="vendorName" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">联系人</label>
            <div class="layui-input-inline">
                <input type="text" name="vendorContact" id="vendorContact" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>
    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">电话</label>
            <div class="layui-input-inline">
                <input type="text" name="vendorPhone" id="vendorPhone" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单人</label>
            <div class="layui-input-inline">
                <input type="text" name="singleMaker" id="singleMaker" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单日期</label>
            <div class="layui-input-inline">
                <input type="text" name="singleTime" id="singleTime" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-inline">
                <input type="text" name="storageRemarks" id="storageRemarks" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>
    <div class="layui-form-item layui-form-text" style="margin-left:130px;margin-top:30px">
        <label class="layui-form-label">审核原因</label>
        <div class="layui-input-block">
            <textarea name="examineReason" id="examineReason" placeholder="请输入审核原因" class="layui-textarea" lay-verify="required"></textarea>
        </div>
    </div>
    <table class="layui-hide" id="auditDetails" lay-filter="test"></table>
    <div class="layui-form-item" style="text-align:center;margin-top:50px">
        <button class="layui-btn" lay-submit lay-filter="demo-login">审核通过</button>
        <button class="layui-btn" lay-submit lay-filter="demo-false">审核不通过</button>
        <button type="reset" class="layui-btn layui-btn-primary" onclick="location.href='/Warehouse/StorageShow'">取消</button>
    </div>
</form>`,
                area: ['1500px', '900px'],
                success: function () {
                    var obj1 = {
                        storageId: 0,
                        storageStatus: '',
                        examineReason: '',
                        examinePeople: '',
                    };
                    // 对弹层中的表单进行初始化渲染
                    //form.render();
                    // 审核通过
                    form.on('submit(demo-login)', function (data) {
                        var field = data.field;
                        obj1.storageId = storageId
                        obj1.examineReason = field.examineReason
                        obj1.examinePeople = "yu"
                        obj1.storageStatus = 2
                        console.log(obj1)
                        $.ajax({
                            url: '/Warehouse/GetStorageAudit',
                            type: 'post',
                            data: { obj1, token: localStorage.getItem("token") },
                            success: function (res) {
                                var res = JSON.parse(res)
                                console.log(field)
                                console.log(res)
                                if (res.code == 1) {
                                    layer.alert("审批成功");
                                    setTimeout(function () {
                                        location.reload();
                                    }, 2000);
                                }
                                else {
                                    layer.alert("操作失败");
                                }
                            }
                        })
                        return false; // 阻止默认 form 跳转
                    });
                    // 审核不通过
                    form.on('submit(demo-false)', function (data) {
                        var field = data.field;
                        obj1.storageId = obj.storageId
                        obj1.examinePeople = "yu"
                        obj1.examineReason = field.examineReason
                        obj1.storageStatus = 3
                        $.ajax({
                            url: '/Warehouse/GetStorageAudit',
                            type: 'post',
                            data: { obj1, token: localStorage.getItem("token") },
                            success: function (res) {
                                var res = JSON.parse(res)
                                console.log(field)
                                console.log(res)
                                if (res.code == 1) {
                                    layer.alert("审批不通过");
                                    setTimeout(function () {
                                        location.reload();
                                    }, 2000);
                                }
                                else {
                                    layer.alert("操作失败");
                                }
                            }
                        })
                        return false; // 阻止默认 form 跳转
                    });
                }
            });
        };
    });

    // 查看详情
    window.storagemodel = function (storageId) {
        // 先根据id获取要编辑的数据，发起Ajax请求
        $.ajax({
            type: "get",
            url: "/Warehouse/GetFanStorage",  // 替换为实际的后台根据id获取数据的接口地址
            data: {
                storageId: storageId,
                token: localStorage.getItem("token")
            },
            success: function (res) {
                try {
                    const { data } = JSON.parse(res);
                    //console.log(data)
                    if (data) {
                        const { storageProductData } = data;
                        var storage = data;
                        console.log(storage);
                        console.log(storageProductData);
                        // 反填表单的函数
                        fillForm(storage); 
                       
                         //渲染表格的函数
                        renderTable(storageProductData);
                        resolve(storage, storageProductData);
                    } else {
                        layui.layer.msg(res.message, { icon: 2 });
                        reject(res.message);
                    }
                } catch (e) {
                    //console.error(e);
                    //layui.layer.msg('数据解析失败，请稍后重试', { icon: 2 });
                    //reject('数据解析失败');
                }
            },
        });
       
        layer.open({
            type: 1,
            title: '入库单详情',
            content: `
                      <form class="layui-form" action="">
    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">入库单号</label>
            <div class="layui-input-inline">
                <input type="text" name="storageNos" id="storageNos" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">入库单类型</label>
            <div class="layui-input-inline">
                <input type="text" id="storageTypes" name="storageTypes" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">入库状态</label>
            <div class="layui-input-inline">
                <input type="text" id="storageStatusTest" name="storageStatusTest" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">供应商编号</label>
            <div class="layui-input-inline">
                <input type="text" name="vendorNo" id="vendorNo" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">供应商名称</label>
            <div class="layui-input-inline">
                <input type="text" name="vendorName" id="vendorName" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">联系人</label>
            <div class="layui-input-inline">
                <input type="text" name="vendorContact" id="vendorContact" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>
    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">电话</label>
            <div class="layui-input-inline">
                <input type="text" name="vendorPhone" id="vendorPhone" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单人</label>
            <div class="layui-input-inline">
                <input type="text" name="singleMaker" id="singleMaker" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">制单日期</label>
            <div class="layui-input-inline">
                <input type="text" name="singleTime" id="singleTime" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>

    <div class="layui-form-item" style="margin-left:150px;margin-top:50px">
        <div class="layui-inline">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-inline">
                <input type="text" name="storageRemarks" id="storageRemarks" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">审核原因</label>
            <div class="layui-input-inline">
                <input type="text" name="examineReason" id="examineReason" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
    </div>
    <table class="layui-hide" id="storageProduct" lay-filter="test"></table>
</form>`,
            area: ['1400px', '800px'],
            success: function () {

                // 对弹层中的表单进行初始化渲染
                //form.render();
            }
        });
    };
    var obj = {
        storageId: 0,
        storageStatus: '',
        examineReason: '',
        examinePeople: '',
        examineTime: '',
    };
    // 反填表单的函数
    function fillForm(storage) {
        $('#storageNos').val(storage.storageNo); 
        $('#storageTypes').val(storage.storageType);
        $('#associateNumber').val(storage.associateNumber);
        $('#vendorNo').val(storage.vendorNo);
        $('#vendorName').val(storage.vendorName);
        $('#vendorContact').val(storage.vendorContact);
        $('#vendorPhone').val(storage.vendorPhone);
        $('#singleMaker').val(storage.singleMaker);
        const date = new Date(storage.singleTime);
        const year = date.getFullYear();
        const month = ("0" + (date.getMonth() + 1)).slice(-2);
        const day = ("0" + date.getDate()).slice(-2);
        const hours = ("0" + date.getHours()).slice(-2);
        const minutes = ("0" + date.getMinutes()).slice(-2);
        $('#singleTime').val(year + "-" + month + "-" + day);
        $('#storageRemarks').val(storage.storageRemarks);
        $('#storageStatusTest').val(storage.storageStatusTest);

        obj.storageId = storage.storageId
        obj.storageStatus = storage.storageStatus
        obj.examineReason = storage.examineReason
        obj.examinePeople = storage.examinePeople
        obj.examineTime = storage.examineTime
        console.log(obj)
        console.log(storage.storageNo)
        // 重新渲染表单元素（如果有）
        //form.render();
    }

    // 渲染表格的函数
    function renderTable(storageProductData) {
        console.log(storageProductData);
        //var storageId = storageProductData.storageId

        layui.use('table', function () {
            var table = layui.table;
            if (storageProductData) {
                var inst = table.render({
                    elem: '#storageProduct', // 对应HTML中表格的id
                    data: storageProductData, // 绑定获取的数据
                    cols: [[
                        { field: 'productName', title: '产品名称' },
                        { field: 'productNo', title: '产品编码' },
                        { field: 'productSpec', title: '规格' },
                        { field: 'batch', title: '批次' },
                        { field: 'price', title: '单价' },
                        { field: 'storageNum', title: '入库数' },
                        { field: 'totalPrice', title: '总价' },
                        { field: 'binLocationName', title: '库位' },
                    ]],
                });
            }
        });
    }
}

// 定义删除数据的函数（此处简单示意，可参考之前详细的删除功能代码完善）
window.deleteData = function (storageProductsId) {
    console.log(storageProductsId)
    layer.confirm('确定要删除该条数据吗？', function (index) {
        $.ajax({
            type: "Post",
            url: "/Warehouse/GetDelectStorage",  // 替换为实际的后台删除数据接口地址
            data: {
                data: JSON.stringify({ storageProductsId: storageProductsId }),
                token: localStorage.getItem("token")
            },
            success: function (res) {
                var res = JSON.parse(res)
                if (res.code === 1) {
                    layer.alert("删除成功");
                    show();  // 重新加载数据，刷新表格显示
                } else {
                    layer.alert("删除失败");

                }
            },
            error: function () {
                layer.msg('删除失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
};

// 点击批量删除按钮的事件处理
$('#batchDeleteBtn').click(function () {
    var table = layui.table;
    // 获取选中行的数据（这里主要是获取warehouseId）
    var checkStatus = table.checkStatus('storageData');
    var selectedIds = checkStatus.data.map(function (item) { return item.storageProductsId; });
    console.log(selectedIds)
    if (selectedIds.length === 0) {
        layer.msg('请至少选择一条要删除的数据', { icon: 2 });
        return;
    }
    layer.confirm('确定要批量删除选中的 ' + selectedIds.length + ' 条数据吗？', function (index) {
        // 发送Ajax请求到后端，传递选中的id数组进行删除操作
        var storageProductsIds = {
            storageProductsId: selectedIds
        }
        console.log(storageProductsIds)
        $.ajax({
            url: '/Warehouse/GetPlDelectStorage', // 后端批量删除接口地址，根据实际调整
            type: 'post',
            data: {
                storageProductsId: storageProductsIds,
                token: localStorage.getItem("token"),
            },
            success: function (res) {
                var res = JSON.parse(res)
                console.log(res)
                if (res.code > 0) {
                    layer.msg('批量删除成功', { icon: 1 });
                    show()
                } else {
                    layer.msg('批量删除失败：' + res.message, { icon: 2 });
                }
                layer.close(index);
            },
            error: function () {
                layer.msg('请求出错，请稍后再试', { icon: 2 });
                layer.close(index);
            }
        });
    });
});

//审批
//layui.use(['layer', 'form', 'table'], function () {
//    var layer = layui.layer;
//    var form = layui.form;
//    var table = layui.table;
   
   
//});

// 点击编辑按钮的事件处理
$('#batchUpdBtn').click(function () {
    var table = layui.table;
    // 获取选中行的数据（这里主要是获取warehouseId）
    var checkStatus = table.checkStatus('storageData');
    var selectedData = checkStatus.data.map(function (item) {
        return item.storageId;
    });
    console.log(selectedData);
    if (selectedData.length === 0) {
        layer.msg("请选择一条要编辑的数据", { icon: 2 });
        return;
    }
    localStorage['storageId'] = selectedData;
    location.href = '/Warehouse/StorageUpd';
});
//入库编辑
window.updateData = function (storageId) {
    localStorage['storageId'] = storageId;
    location.href = '/Warehouse/StorageUpd';
}
// 定义时间格式转换函数
function formatTime(timeStamp) {
    if (timeStamp) {
        var date = new Date(timeStamp);
        var year = date.getFullYear(); // 获取年份
        var month = ('0' + (date.getMonth() + 1)).slice(-2); // 获取月份，+1是因为getMonth()返回的月份是从0开始计数的
        var day = ('0' + date.getDate()).slice(-2); // 获取日期
        var hour = ('0' + date.getHours()).slice(-2); // 获取小时
        var minute = ('0' + date.getMinutes()).slice(-2); // 获取分钟
        var second = ('0' + date.getSeconds()).slice(-2); // 获取秒
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return "";
}